import requests
import numpy
import re
import ConnectMySql
from concurrent.futures import ThreadPoolExecutor

conn, cursor = ConnectMySql.openConn()
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.41',
    'cookie': '_ga=GA1.2.1784463723.1676113071; _gid=GA1.2.1404992785.1676113071; gtoken=W8biQLhCdWWf; gid=0d23b661-ba49-4c05-b5a8-bd2b17b74548; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1676113071,1676186100; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1676189236; _gat=1; kw_token=4EIZRU47CD8',
    'Connection': 'keep-alive'
}


def getSingerMessage(url, id):
    response = requests.get(url, headers=headers).text
    artistInfo = r'<span class="text" data-v-0b25de6a>(.*?)</span>'
    artistList = re.findall(artistInfo, response, re.S)
    introduceReg = r'<p class="info" data-v-0b25de6a>(.*?)</p>'
    introduceList = re.findall(introduceReg, response, re.S)
    try:
        cursor.execute(
            "update singer set sname=%s, alias=%s, sex=%s, country=%s, bornplace=%s, language=%s, birthday=%s, constellation=%s, height=%s, weight=%s, introduce=%s where sid=%s",
            (artistList[0], artistList[1], artistList[2], artistList[3], artistList[4], artistList[5], artistList[6],
             artistList[7],
             artistList[8], artistList[9], introduceList[0], id))
        conn.commit()
        print(f'{id} 歌手信息已录入')
    except Exception as e:
        print(f'{url} 获取歌手信息异常, 1S 后重试')
        # Timer(1, getSingerMessage, (url, id)).start()
        pass


if __name__ == '__main__':
    executor = ThreadPoolExecutor(max_workers=10)

    cursor.execute("select sId from singer where sname is null")
    singerArray = cursor.fetchall()
    singerArray = numpy.array(singerArray)
    # for i in range(len(nameArray)):
    #     url = "http://www.kuwo.cn/singer_detail/" + str(nameArray[i][0]) + "/info"
    #     getSingerMessage(url, nameArray[i][0])

    for singer in singerArray:
        s = str(singer[0])
        getSingerMessage(f'http://www.kuwo.cn/singer_detail/{s}/info', s)
    #     future = executor.submit(getSingerMessage, f'http://www.kuwo.cn/singer_detail/{s}/info', s)
    # executor.shutdown(wait=True)

    # all_task = [executor.submit(getSingerMessage, (
    #     f'http://www.kuwo.cn/singer_detail/{str(singer[0])}/info'))
    #             for singer in singerArray]

    # wait(all_task, return_when=ALL_COMPLETED)

    ConnectMySql.closeConn(conn, cursor)
